package com.teacold.customdemo.chapter_seven;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.widget.TextView;

public class ShimmerTextView extends TextView {
    private int mDx;
    private LinearGradient mLinearGradient;
    private Paint mPaint;

    public ShimmerTextView(Context context) {
        this(context,null);
    }

    public ShimmerTextView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ShimmerTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
         mPaint=getPaint();
         int length= (int) mPaint.measureText(getText().toString());
           createAnim(length);
        createLinearGradient(length);



    }

    private void createLinearGradient(int length) {
        mLinearGradient=new LinearGradient(-length,0,0,0,new int[]{getCurrentTextColor(),0xff00ff00,getCurrentTextColor()},new float[]{0,0.5f,1},Shader.TileMode.CLAMP);


    }

    private void createAnim(int length) {
        ValueAnimator valueAnimator=ValueAnimator.ofInt(0,2*length);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
               mDx= (int) animation.getAnimatedValue();
               invalidate();
            }
        });
        valueAnimator.setRepeatMode(ValueAnimator.RESTART);
        valueAnimator.setRepeatCount(ValueAnimator.INFINITE);
        valueAnimator.setDuration(2000);
        valueAnimator.start();


    }

    @Override
    protected void onDraw(Canvas canvas) {
        Matrix matrix=new Matrix();
        matrix.setTranslate(mDx,0);
        mLinearGradient.setLocalMatrix(matrix);
        mPaint.setShader(mLinearGradient);
        super.onDraw(canvas);
    }
}
